#include "Socket.h"
#include "Client.h"
#include "Server.h"
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <string>
#include <cjson/cJSON.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <pthread.h>
#include "../include/menu.h"
#include "../include/MyClient.h"
#include "../include/header.h"
using namespace std;
extern Menu menu;

void *recvMSGThread(void *client);

int main(int argc, char const *argv[])
{
    char *msg = new char[1024];
    MyClient client(SOCK_STREAM, 8848, (char *)"0.0.0.0");

    for (int i = 0; i < 3; i++)
    {
        menu.show();
        client.login();
        client.receiveMsg();
        if (string(client.data_) == "success")
        {
            break;
        }
        else
        {
            cout << "username or password is incorrect.\n\n\n" << endl;
            if (i == 2)
                exit(1);
        }
    }
    cout << "\n\nWelcom!\nLogin successfully.\n\n";
    pthread_t recv_tid;
    pthread_create(&recv_tid, NULL,
                   recvMSGThread, &client);

    char *tmp = new char[1024];
    while (fgets(msg, 1024, stdin) != NULL)
    {
        msg[strlen(msg) - 1] = 0; //最后一个字符是回车，因此删除
        if (strcmp(msg, "exit") == 0)
        {
            while (true)
            {
                cout << "Send the message or exit?" << endl;
                cout << "If you want to send the message, please enter 'send'.";
                cout << "Or enter 'exit' to exit the program." << endl;
                string exit;
                cin >> exit;
                if (exit == "send")
                {
                    client.sendMsg(msg, strlen(msg));
                    break;
                }
                if (exit == "exit")
                    return 0;
                cout << "Yout input error!\n\n"
                     << endl;
            }
        }
        else
        {
            strcpy(tmp, client.username_);
            int len = strlen(tmp);
            tmp[len] = ':';
            tmp[len + 1] = '\n';
            tmp[len + 2] = ' ';
            tmp[len + 3] = ' ';
            tmp[len + 4] = '\0';
            strcat(tmp, msg);
            client.sendMsg(tmp, strlen(tmp));
        }
    }
    pthread_join(recv_tid, NULL);
    return 0;
}

void *recvMSGThread(void *cli)
{
    MyClient *client = (MyClient *)cli;
    while (true)
    {
        client->receiveMsg();
        cout << client->data_ << endl;
    }
}
